package com.www.jpa.service;

import com.xxx.annotation.TimeCost;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.sql.DataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class UserServiceImpl {

    @Autowired
    private DataSource dataSource;

    @TimeCost
    @Transactional
    public void jdbcBatchInsert(int count) throws SQLException {
        try (Connection connection = dataSource.getConnection();
             PreparedStatement ps = connection.prepareStatement(
                     "INSERT INTO t_user (username, age) VALUES (?, ?)")) {
            connection.setAutoCommit(false);
            for (int i = 1; i <= count; i++) {
                ps.setString(1, "须知少时凌云志, 曾许人间第一流 " + i);
                ps.setInt(2, (int) (Math.random() * 100));
                ps.addBatch();
                if (i % 5000 == 0) {
                    log.info("开始插入{}条数据。。。", i);
                    ps.executeBatch();
                    connection.commit();
                }
            }

            // 最后插入剩余的数据
            ps.executeBatch();
            connection.commit();
            log.info("成功插入{}条数据", count);
        } catch (Exception e) {
            log.error("msg={}", e.getMessage(), e);
        }
    }


    @TimeCost
    @Transactional
    public void jdbcBatchUpdate(int count) throws SQLException {
        try (Connection connection = dataSource.getConnection();
             PreparedStatement ps = connection.prepareStatement(
                     "UPDATE t_user set age=18 where id=?")) {
            connection.setAutoCommit(false);
            for (int i = 0; i < count; i++) {
                ps.setInt(1, i);
                ps.addBatch();
                if (i % 5000 == 0) {
                    log.info("开始修改{}条数据。。。", i);
                    ps.executeBatch();
                    connection.commit();
                }
            }

            // 最后插入剩余的数据
            ps.executeBatch();
            connection.commit();
            log.info("成功修改{}条数据", count);
        } catch (Exception e) {
            log.error("msg={}", e.getMessage(), e);
        }
    }
}
